<template>
    <view class="container">
        <!-- @scrolltolower="scrolltolower" -->
        <!-- <scroll-view scroll-y="true" class="scroll"> -->
        <view class="detail-head">
            <view class="head-top row">
                <view class="head-info">
                    <view class="title">
                        团意保
                    </view>
                    <view class="name">
                        商务负责人：{{ detailInfo?.wesureInfo?.salesName }}
                    </view>
                </view>
                <view :class="['head-close', detailInfo?.wesureInfo?.serviceState === 2 ? 'head-close-grey' : '']">
                    {{ detailInfo?.wesureInfo?.serviceState === 1 ? '已交付' : detailInfo?.wesureInfo?.serviceState === 2 ?
                        '已关闭' : '已开通' }}
                </view>
            </view>
            <view class="company-box">
                <view class="company-customer" @click="onGoContact">
                    <view>
                        关联客户：
                    </view>
                    <view class="title">
                        {{ detailInfo?.wesureInfo?.companyName }}
                        <image src="@/static/home/right-arrow.png" class="arrow-img" />
                    </view>
                </view>
                <view class="company-contacts" @click="onGoCustomer">
                    <view>客户联系人：</view>
                    <view class="title">
                        <view class="contacts-list">
                            <view class="portrait-i" v-for="(item, index) in detailInfo.relevantContacts" :key="index">
                                <default-portrait :name="item.customName" url="" width="48" height="48" />
                            </view>
                        </view>
                        {{ detailInfo?.relevantContacts?.length }}人
                        <image src="@/static/home/right-arrow.png" class="arrow-img" />
                    </view>
                </view>
            </view>
        </view>
        <!-- 子弹发薪列表 -->
        <view>
            <view class="tab-radius">
                <tabRadius :list="['详细信息', '投保及运营数据']" :active="payIndex" @change="onPayTab" divided="100%" />
            </view>
            <!-- 详细订单 -->
            <view class="record-list" v-if="payIndex === 0">
                <view class="record-i">
                    <view class="i-info">
                        <view class="info-row row">
                            <view class="info-row-left"> 产品开通时间： </view>
                            <text class="info-row-right">{{ detailInfo?.productOpenTime?.productOpenTime }}</text>
                        </view>
                        <view class="info-row row">
                            <view class="info-row-left"> 最后修改负责人时间： </view>
                            <text class="info-row-right">{{ detailInfo?.productOpenTime?.updateSalerTime }}</text>
                        </view>
                        <view class="info-row row">
                            <view class="info-row-left"> 备注： </view>
                            <text class="info-row-right">{{ detailInfo?.productOpenTime?.remark || '——' }}</text>
                        </view>
                    </view>
                </view>
            </view>
            <!-- 销售记录 -->
            <view class="operate-box" v-if="payIndex === 1">
                <view class="operate">
                    <view class="operate-screen operate-screen-active row">
                        <picker @change="onChangeCompany" :range="gcpabaosi" mode="selector" class="month-select">
                            <view class="screen-i screen-i-active row">
                                {{ gcpabaosi[insureCompanyIndex] }}
                                <image class="drop-down" src="@/static/drop-down.png" mode="scaleToFill" />
                            </view>
                        </picker>
                        <picker @change="onChangeProgramme" :range="insuranceDate" mode="selector" class="month-select">
                            <view class="screen-i screen-i-active row">
                                {{ insuranceDate[programmeIndex] }}
                                <image class="drop-down" src="@/static/drop-down.png" mode="scaleToFill" />
                            </view>
                        </picker>
                        <view class=" row">
                            <poput-time :list='selectTimeList' :default="timeIndex" @cancel="onCancel" />
                            <!-- <uni-datetime-picker v-model="rangeTime" type="daterange" @change="onRangeTime">
                                    {{ startTime }}至{{ endTime }}
                                </uni-datetime-picker> -->
                        </view>
                    </view>
                    <view>
                        <view class="box-list">
                            <view class="block-box-i block-box-i-active">
                                <view class="title">
                                    保费
                                </view>
                                <view class="num">
                                    <text class="company">￥</text>{{ statisticsInfo.amount }}
                                </view>
                            </view>
                        </view>
                        <view class="box-list">
                            <view class="block-box-i">
                                <view class="title">
                                    投保人数
                                </view>
                                <view class="num">
                                    {{ statisticsInfo.policyPeopleCount }}
                                </view>
                            </view>
                            <view class="block-box-i">
                                <view class="title">
                                    报案数
                                </view>
                                <view class="num">
                                    {{ statisticsInfo.recordCount }}
                                </view>
                            </view>
                        </view>
                    </view>
                </view>
                <view class="operate operate-top">
                    <view class="operate-title row">
                        <view class="title">方案统计</view>
                        <view class="operate-screen row">
                            <!-- <uni-datetime-picker v-model="chartTime" >{{ chartTime }}月</uni-datetime-picker> -->
                            <picker @change="onInsuranceMonthChange" mode="date" fields="month" class="month-select">
                                <view class="screen-i">
                                    <text>{{ chartTime }}</text>
                                    <view class="triangle" />
                                </view>
                            </picker>
                        </view>
                    </view>
                    <noData v-if="chartsDataPie1.series[0].data.length === 0" />
                    <view class="operate-chart" v-show="chartsDataPie1.series[0].data.length">
                        <qiun-data-charts canvas2d canvasId="operate-charts" class="qiun-data-charts" type="ring"
                            :opts="optsRing" :chartData="chartsDataPie1" />
                    </view>
                    <view class="operate-table">
                        <view class="table-title row">
                            <view class="title">保险方案</view>
                            <view class="title">保费</view>
                            <view class="title">占比</view>
                        </view>
                        <view class="table-cell row" v-for="(item, index) in chartsDataPie1.series[0].data" :key="index">
                            <view class="cell cell-active">
                                <view class="colour-block" :style="{ background: item.color }"></view>
                                {{ item.name }}
                            </view>
                            <view class="cell">¥{{ item.value }}</view>
                            <view class="cell">{{ (item.value / item.totalPremium * 100).toFixed(2) }}%</view>
                        </view>
                    </view>
                </view>
            </view>
        </view>
        <!-- </scroll-view> -->
    </view>
</template>
<script setup lang="ts">
import { onLoad, onShow } from '@dcloudio/uni-app'
import { ref } from 'vue'
import tabRadius from '@/components/tab-radius/tab-radius.vue'
import uchartsOpts from '@/utils/ucharts'
import { getInsure, getInsureStatistics, getInsureChart, GetInsureDto, getInsureCompany, getInsureProgramme } from '@/api/signing'
import { dateFormat } from '@/utils/util'
import poputTime from '@/components/popup-custom-time/popup-custom-time.vue'
import { InsureCompanyDto } from '@/api/dto'
import defaultPortrait from '@/components/default-portrait/default-portrait.vue'
import noData from '@/components/no-data/no-data.vue'
const dealId = ref()
const payIndex = ref(0)
const rangeTime = ref()
const startTime = ref('')
const endTime = ref('')
const cstartTime = ref('')
const cendTime = ref('')
const companyId = ref()
const detailInfo = ref({} as GetInsureDto)
const statisticsInfo = ref({} as { amount: number, policyPeopleCount: number, recordCount: number })
const chartTime = ref('')
const optsRing = ref(uchartsOpts.optsRing)
const programmeList = ref(['全部方案'] as string[])
const programmeIndex = ref(0)
const customer = ref('day')
const insureCompany = ref([{
    insureCompanyType: '',
    name: '全部保司'
}] as InsureCompanyDto[])
const insureCompanyIndex = ref(0)
const chartsDataPie1 = ref({
    series: [{
        data: []
    }]
} as { series: { data: { name: string, value: number }[] }[] })
const selectTimeList = ref(['昨天', '今天', '本周', '本月', '上月'])
const timeIndex = ref(3)
// show: false
onLoad((options) => {
    console.log(options, 'options')
    const nowyear = new Date().getFullYear()
    const nowmonth = new Date().getMonth() + 1
    cstartTime.value = formatDate(new Date(nowyear, nowmonth - 1, 1))
    cendTime.value = formatDate(new Date(nowyear, nowmonth, 0))
    companyId.value = options.id
    dealId.value = options.dealId
    chartTime.value = dateFormat('YY-mm', new Date())
    getInsureStatisticsInfo()
    getInsureChartInfo()
    getInsureCompanyList()
    getInsureProgrammeList()
})
const formatDate = (date: any) => {
    const myyear = date.getFullYear()
    let mymonth = date.getMonth() + 1
    let myweekday = date.getDate()
    if (mymonth < 10) {
        mymonth = "0" + mymonth
    }
    if (myweekday < 10) {
        myweekday = "0" + myweekday
    }
    return (myyear + "-" + mymonth + "-" + myweekday)
}
onShow(() => {
    getInsureInfo()
})
// 去关联客户
const onGoCustomer = async () => {
    uni.navigateTo({
        url: '/packageRemind/pages/related-contacts/related-contacts?dealId=' + dealId.value + '&companyId=' + companyId.value
    })
}
// // 去客户联系人
// const onGoContact = () => {
//     uni.navigateTo({
//         url: '/packageRemind/pages/customer-detail/index?id=' + companyId.value + '&customer=' + customer.value + '&dealId=' + dealId.value
//     })
// }
const onCancel = async (index: { index: number, time: undefined | string }) => {
    console.log(index)
    timeIndex.value = Number(index.index)
    console.log(index, 'index')
    startTime.value = index.time?.split(' 至 ')[0] as string
    endTime.value = index.time?.split(' 至 ')[1] as string
    cstartTime.value = index.startTime
    cendTime.value = index.endTime
    await getInsureStatisticsInfo()
}
// 信息
const getInsureInfo = async () => {
    // companyId.value
    const result = await getInsure({
        companyId: companyId.value,
        dealId: dealId.value
    })
    detailInfo.value = result
}
// 统计信息
const getInsureStatisticsInfo = async () => {
    console.log(programmeList.value[programmeIndex.value], 'programmeList.value[programmeIndex.value]')
    // companyId.value
    const result = await getInsureStatistics({
        companyId: companyId.value,
        startTime: timeIndex.value > 800 ? startTime.value : cstartTime.value,
        endTime: timeIndex.value > 800 ? endTime.value : cendTime.value,
        insureCompanyType: 'insure_type_tyrb',
        insurCompanyCode:
            insureCompanyIndex.value === 0
                ? ''
                : allCompany.value[insureCompanyIndex.value - 1].insurCompany || '',
        tyxPlanName:
            programmeIndex.value === 0
                ? ''
                : insurancePlans.value[programmeIndex.value - 1].wesurePlanName || ''
    })
    statisticsInfo.value = result
}
// 图表数据
const getInsureChartInfo = async () => {
    const result = await getInsureChart({
        companyId: companyId.value,
        queryMonth: chartTime.value,
        insureCompanyType: 'insure_type_tyrb'
    })
    chartsDataPie1.value.series[0].data = result.map((item: { programme: string, premium: number }) => {
        return {
            name: item.programme,
            value: item.premium,
            ...item
        }
    })
    console.log(chartsDataPie1.value.series[0].data, 'chartsDataPie1')
}

// const allInsCompany = ref([] as string[])
const allCompany = ref()
const longCompanyName = ref([] as string[])
// 获取保司列表 getInsureCompany
const getInsureCompanyList = async () => {
    allCompany.value = await getInsureCompany(3)
    const arr = allCompany.value.map((ele) => {
        return ele.name
    })
    arr.unshift('全部保司')
    console.log(arr, 'csj')
    gcpabaosi.value = arr
    // console.log(allCompany.value, '保司列表是啥。')
    // console.log(allCompany.value, 'allCompanyallCompanyallCompany')
    // // push 推送  合并数组
    // allCompany.value.forEach((item:any, index:number) =>
    //   longCompanyName.value = [{...[allCompany.value[index].dictSort , allCompany.value[index].dictLabel]}, ...longCompanyName.value],
    // )
    // // longCompanyName.value = [...['全部保司']],
    // console.log(longCompanyName.value, 'allCompanyallCompany')
    // longCompanyName.value.forEach((item:any, index:number) => {
    //   console.log(item[0], item[1], '000000000000000000000')
    //   insureCompany.value[item[0] + 1] = item[1] // 每一项赋值进去。
    // })
    // insureCompany.value[0] = '全部保司' // 第0项赋值
    // console.log(insureCompany.value, '111111111111111111111111111111111')
    // // insureCompany.value.push(...result)
}
const gcpabaosi = ref([])
// 修改保思
const onChangeCompany = async (event: { detail: { value: string } }) => {
    console.log(event, 'event')
    insureCompanyIndex.value = Number(event.detail.value)
    await getInsureStatisticsInfo()
}
// 获取保险方案列表 getInsureProgramme
const getInsureProgrammeList = async () => {
    const result = await getInsureProgramme({
        companyId: companyId.value,
        insureCompanyType: 'insure_type_tyrb'
    })
    insurancePlans.value = result
    const arr = result.map((ele) => {
        return ele.wesurePlanName
    })
    arr.unshift('全部方案')
    // 保险方案数据赋值
    insuranceDate.value = arr
}
const insurancePlans = ref<any>([])
const insuranceDate = ref<any>([])
const onChangeProgramme = async (event: { detail: { value: string } }) => {
    programmeIndex.value = Number(event.detail.value)
    await getInsureStatisticsInfo()
}
// 改变月
const onInsuranceMonthChange = (event: { detail: { value: string } }) => {
    chartTime.value = event.detail.value
    getInsureChartInfo()
}
// tab发薪胶囊回调
const onPayTab = (index: number) => {
    payIndex.value = index
}
// 返回时间
const onRangeTime = (time: string[]) => {
    console.log(time)
    startTime.value = dateFormat('mm/dd', new Date(time[0]))
    endTime.value = dateFormat('mm/dd', new Date(time[1]))
    getInsureStatisticsInfo()
}
</script>
<style lang="scss" scoped>
.container {
    min-height: 100vh;
    background: #fafafc;
    padding-bottom: 0;
}

.tab-box {
    display: flex;
    align-items: center;
    justify-content: center;
}

.tab-radius {
    margin-top: 30rpx;
    padding: 0rpx 30rpx;
}

.scroll {
    height: 100vh;
}

.record-list {
    padding: 0 30rpx;
    margin-top: 34rpx;

    .record-i {
        padding: 30rpx;
        background: #ffffff;
        border-radius: 16rpx;
    }

    .info-row {
        display: flex;
    }

    .info-row-left {
        color: $grey;
        font-size: $font-normal;
        margin-bottom: 17rpx;
    }

    .info-row-right {
        color: $black;
        font-size: $font-normal;
        margin-bottom: 17rpx;
    }
}

.operate-box {
    padding: 30rpx;
}

.operate {
    padding: 30rpx;
    background: #FFFFFF;
    border-radius: 16rpx;

    .screen-i {
        border-radius: 8rpx;
        border: 1rpx solid #DEE0E3;
        padding: 12rpx 15rpx;
        color: #565868;
        font-size: $font-base;
    }

    .drop-down {
        width: 22rpx;
        height: 20rpx;
    }

    .box-list {
        @include flex-between;
        flex-wrap: wrap;
        margin: 30rpx 0 30rpx 0;
    }

    .block-box-i {
        width: calc(100% / 2.3);
        background: #F4F4F7;
        padding: 23rpx 0 23rpx 30rpx;
        border-radius: 16rpx;

        .title {
            color: #565868;
            font-weight: bold;
        }

        .num {
            color: $black;
            font-weight: bold;
            font-size: $font-large;
            margin-top: 10rpx;
        }

        .company {
            font-size: $font-small;
        }
    }

    .block-box-i-active {
        flex: 1;
    }

}

.operate-top {
    margin-top: 30rpx;

    .operate-title {
        title {
            color: $black;
            font-size: $font-normal;
        }
    }

    .operate-chart {
        margin-top: 52rpx;
        height: 400rpx;
    }

    .qiun-data-charts {
        height: 400rpx;
        width: 200rpx;
    }

}

.operate-screen-active {
    display: flex;
    align-items: center;
    justify-content: flex-end;

    .screen-i-active {
        margin-right: 16rpx;
    }
}

.contacts-list {
    margin-right: 40rpx;
}

.portrait-i {
    margin-right: -20rpx;
}

.cell {
    font-size: 24rpx;
}
</style>
